package com.androidbegin.jsonparsetutorial;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {

	// Declare Variables
	Context context;
	LayoutInflater inflater;
	ArrayList<HashMap<String, String>> data;
	ImageLoader imageLoader;
	HashMap<String, String> resultp = new HashMap<String, String>();

	public ListViewAdapter(Context context,
			ArrayList<HashMap<String, String>> arraylist) {
		this.context = context;
		data = arraylist;
		imageLoader = new ImageLoader(context);
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	static class ViewHolder {
		TextView rank;
		TextView country;
		ImageView flag;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = new ViewHolder();
		if (convertView == null) {
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.listview_item, parent,
					false);
			resultp = data.get(position);
			viewHolder.rank = (TextView) convertView.findViewById(R.id.rank);
			viewHolder.country = (TextView) convertView
					.findViewById(R.id.country);
			viewHolder.flag = (ImageView) convertView.findViewById(R.id.flag);
			viewHolder.rank.setText(resultp.get(MainActivity.ID));
			viewHolder.country.setText(resultp.get(MainActivity.CONTENT));
			imageLoader.DisplayImage(resultp.get(MainActivity.IMAGE),
					viewHolder.flag);
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// Get the position
					resultp = data.get(position);
					Intent intent = new Intent(context, SingleItemView.class);
					// Pass all data rank
					intent.putExtra("id", resultp.get(MainActivity.ID));
					// Pass all data country
					intent.putExtra("content_detail",
							resultp.get(MainActivity.CONTENT));
					// Pass all data population
					// Pass all data flag
					intent.putExtra("image_thumbnail",
							resultp.get(MainActivity.IMAGE));
					// Start SingleItemView Class
					context.startActivity(intent);

				}
			});
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		return convertView;
	}
}
